package com.eastedu.superise.handler.question.handler.answerparentheses.underline;

import com.eastedu.common.enums.MediaTypeEnum;
import com.eastedu.common.model.question.Fragment;
import com.eastedu.common.model.question.QuestionItemContent;
import com.eastedu.superise.handler.question.handler.ContentParser;
import com.eastedu.superise.handler.question.handler.answerparentheses.ContentSummary;
import com.eastedu.superise.handler.question.handler.PatternConstant;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.regex.Matcher;
import java.util.stream.Collectors;

/**
 * 解析选择题干的括号内容
 *
 * @author Administrator
 */
@Slf4j
public class StemUnderlineContentParser implements ContentParser<ContentSummary> {
    private final Set<Long> questions = Sets.newConcurrentHashSet();
    @Override
    public ContentSummary parse(Long questionId, List<QuestionItemContent> contents) {
        // 添加试题
        questions.add(questionId);
        // 第一步提取内容
        String contentString = contents.stream()
                .map(QuestionItemContent::getFragments)
                .flatMap(Collection::stream)
                .filter(fragment -> fragment.getMediaType() != MediaTypeEnum.FORMULA)
                .map(Fragment::getContent)
                .collect(Collectors.joining());


        Map<Optional<String>, List<String>> details = new HashMap<>(10);
        Matcher matcher = PatternConstant.ANSWER_PARENTHESES_UNDERLINE_PATTERN.matcher(contentString);
        while (matcher.find()) {
            String parentheses = matcher.group("parentheses");
            details.computeIfAbsent(Optional.ofNullable(parentheses), s -> new ArrayList<>()).add(parentheses);
            // 如果发现了下划线，再次校验片段中是否有下划线。如果没有，说明下划线被分割了，记录该试题，否则移除试题
            contents.stream()
                    .map(QuestionItemContent::getFragments)
                    .flatMap(Collection::stream)
                    .map(Fragment::getContent)
                    .forEach(content -> {
                        Matcher matcher0 = PatternConstant.ANSWER_PARENTHESES_PATTERN.matcher(content);
                        while (matcher0.find()) {
                            questions.remove(questionId);
                        }
                    });
        }
        return new ContentSummary(details);
    }

    @Override
    public void print() {
        log.info("下划线异常的试题: {}", questions);
    }
}
